<template>
  <el-dialog v-model="visible" title="加课" width="50%" top="5vh">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="教师" prop="teacherId">
        <el-select v-model="form.teacherId" placeholder="选择教师" clearable filterable remote
          :remote-method="queryTeacher">
          <el-option v-for="teacher in teachers" :key="teacher.id" :label="teacher.teacherName" :value="teacher.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="加课时间" prop="scheduleTime">
        <el-date-picker style="width: 100%;" v-model="form.scheduleTime" type="datetime" placeholder="选择上课时间"
          value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
  courseData: Object,
  teachers: Array,
  queryTeacher: Function,
  instrumentsOptions: Array
})

const emit = defineEmits(['update:modelValue', 'success', 'updateTeachers'])

const visible = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  teacherId: '',
  scheduleTime: '',
})

// 表单验证规则
const rules = {
  teacherId: [{ required: true, message: '请选择教师', trigger: 'change' }],
  scheduleTime: [{ required: true, message: '请选择上课时间', trigger: 'change' }],
}

// 监听显示状态
watch(() => props.modelValue, (val) => {
  visible.value = val
  // 处理教师数据
  emit('updateTeachers', [{
    id: props.courseData.teacherId,
    teacherName: props.courseData.teacherName
  }])
  form.teacherId = props.courseData.teacherId
  form.scheduleTime = props.courseData.scheduleTime
  
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 处理数据
    const submitData = { ...form }
    ElMessage.success('加课成功')

    emit('success', submitData)
    visible.value = false
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

</script>
